//
//  CloseAreaViewController.m
//  Logistics
//
//  Created by 华谕 on 2017/11/2.
//  Copyright © 2017年 HUYU. All rights reserved.
//

#import "CloseAreaViewController.h"
#import "CityModel.h"

static NSString * CellIdentifier = @"closeAreaCell";
@interface CloseAreaViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic, strong)UICollectionView *collectionView;
@property (nonatomic, strong)NSArray *ProvinceAry;
@property (nonatomic, strong)NSArray *cityAry;
@property (nonatomic, strong)NSArray *districtAry;
@property (nonatomic, assign)NSInteger leverType;

@end

@implementation CloseAreaViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _leverType = 1;
    [self creatUI];
    if (_areaType == 1)
    {
        NSDictionary *dic = @{@"level":@"1"};
        [self requestAreaList:dic CityModel:nil];
    }
    else if (_areaType == 2)
    {
        NSDictionary *dic = @{@"level":@"1",
                              @"shipmentId":_shipmentId
                              };
        [self requestAreaList:dic CityModel:nil];
    }
   
}

- (void)creatUI
{
    self.navigationItem.title = @"选择城市";
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor whiteColor];

    //此处必须要有创见一个UICollectionViewFlowLayout的对象
    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init];
    //同一行相邻两个cell的最小间距
    layout.minimumInteritemSpacing = 0;
    //最小两行之间的间距
    layout.minimumLineSpacing = 0;
    _collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(20*displaywidth, 15*displayheight, SCREEN_WIDTH-40*displaywidth, SCREEN_HEIGHT-STA_NAV_HEIGHT-60*displayheight-SCREER_HeiX) collectionViewLayout:layout];
    _collectionView.backgroundColor=[UIColor whiteColor];
    _collectionView.delegate=self;
    _collectionView.dataSource=self;
    [self.view addSubview:_collectionView];
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:CellIdentifier];
    
    UIButton *cancelBtn = [ZCControl createButtonWithFrame:CGRectMake(25*displaywidth, SCREEN_HEIGHT-STA_NAV_HEIGHT-60*displayheight-SCREER_HeiX, SCREEN_WIDTH/2-40*displaywidth, 40*displayheight) ImageName:nil Target:self Action:@selector(cancelAction) Title:@"取消" Font:16.0];
    cancelBtn.backgroundColor = RGB(232, 232, 232);
    [cancelBtn setTitleColor:RGB(204, 204, 204) forState:UIControlStateNormal];
    cancelBtn.layer.cornerRadius = 5;
    cancelBtn.layer.masksToBounds = YES;
    [self.view addSubview:cancelBtn];
    
    UIButton *backBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH/2+15*displaywidth, SCREEN_HEIGHT-STA_NAV_HEIGHT-60*displayheight-SCREER_HeiX, SCREEN_WIDTH/2-40*displaywidth, 40*displayheight) ImageName:nil Target:self Action:@selector(backAction) Title:@"返回上一级" Font:16.0];
    backBtn.backgroundColor = RGB(255, 153, 0);
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    backBtn.layer.cornerRadius = 5;
    backBtn.layer.masksToBounds = YES;
    [self.view addSubview:backBtn];
}

- (void)cancelAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)backAction
{
    if (_leverType == 1)
    {
        return;
    }
    _leverType--;
    [self.collectionView reloadData];
    
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_leverType == 1)
    {
        return _ProvinceAry.count;
    }
    else if (_leverType == 2)
    {
        return _cityAry.count;
    }
    else
    {
        return _districtAry.count;
    }
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    for (id subView in cell.contentView.subviews) {
        [subView removeFromSuperview];
    }
    CGFloat W = (SCREEN_WIDTH-40*displaywidth)/4-10*displaywidth;
    CityModel * model;
    if (_leverType == 1)
    {
        if (_ProvinceAry.count > 0)
        {
            model = _ProvinceAry[indexPath.row];
        }
    }
    else if (_leverType == 2)
    {
        if (_cityAry.count > 0)
        {
            model = _cityAry[indexPath.row];
        }
    }
    else
    {
        if (_districtAry.count > 0)
        {
            model = _districtAry[indexPath.row];
        }
        
    }
    if (model)
    {
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(5*displaywidth, 5*displayheight, W, 30*displayheight)];
        label.font = NormalFontWithSize(14.0 + fontScale);
        label.text = model.name;
        label.textAlignment = NSTextAlignmentCenter;
        label.layer.cornerRadius = 5;
        label.layer.masksToBounds = YES;
        label.backgroundColor = RGB(232, 232, 232);
        label.textColor = RGB(102, 102, 102);
        if (model.isSelect)
        {
            label.backgroundColor = ThemeColor;
            label.textColor = [UIColor whiteColor];
        }
        [cell.contentView addSubview:label];
    }
    return cell;
}

//定义每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((SCREEN_WIDTH-40*displaywidth)/4, 40*displayheight);
}

//cell的点击事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //cell被电击后移动的动画
    [collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionTop];
    CityModel *model;
    if (_leverType == 1)
    {
        if (_ProvinceAry.count > 0)
        {
            model = _ProvinceAry[indexPath.row];
            for (CityModel *theModel in _ProvinceAry)
            {
                theModel.isSelect = NO;
            }
        }
    }
    else if (_leverType == 2)
    {
        if (_cityAry.count > 0)
        {
            model = _cityAry[indexPath.row];
            for (CityModel *theModel in _cityAry)
            {
                theModel.isSelect = NO;
            }
        }
    }
    else
    {
        if (_districtAry.count > 0)
        {
            model = _districtAry[indexPath.row];
            for (CityModel *theModel in _districtAry)
            {
                theModel.isSelect = NO;
            }
        }
        
    }
    if (model)
    {
        model.isSelect = YES;
        if (_leverType == 3)
        {
            if (self.closeBlock != nil)
            {
                if (_districtAry.count == 1 && [[model.name substringToIndex:1] isEqualToString:@"全"])
                {
                    model.name = [model.name substringFromIndex:1];
                }
                self.closeBlock(model.name, [NSString stringWithFormat:@"%ld",model.ID]);
            }
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
        _leverType++;
        NSDictionary *dic = @{@"level":[NSString stringWithFormat:@"%ld",_leverType],
                              @"parentId":[NSString stringWithFormat:@"%ld",model.ID]
                              };
        if (_areaType == 2)
        {
            dic = @{@"level":[NSString stringWithFormat:@"%ld",_leverType],
                    @"parentId":[NSString stringWithFormat:@"%ld",model.ID],
                    @"shipmentId":_shipmentId
                    };
            
        }
        CityModel *prentModel = [[CityModel alloc] init];
        prentModel.name = model.name;
        prentModel.ID = model.ID;
        prentModel.parentId = model.parentId;
        
        [self requestAreaList:dic CityModel:prentModel];
    }
    
}

- (void)requestAreaList:(NSDictionary *)dic CityModel:(CityModel *)model
{
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestStartAreaListParmers:dic SelectType:_areaType Success:^(id obj) {
        [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
        if ([obj server_Getcodecheck])
        {
            if (_leverType == 1)
            {
                _ProvinceAry = [CityModel mj_objectArrayWithKeyValuesArray:obj[@"data"]];
            }
            else if (_leverType == 2)
            {
                _cityAry = [CityModel mj_objectArrayWithKeyValuesArray:obj[@"data"]];
            }
            else
            {
                _districtAry = [CityModel mj_objectArrayWithKeyValuesArray:obj[@"data"]];
                if (_districtAry.count == 0)
                {
                    if (self.closeBlock != nil)
                    {
                        self.closeBlock(model.name, [NSString stringWithFormat:@"%ld",model.ID]);
                    }
                    [self.navigationController popViewControllerAnimated:YES];
                    return;
//                    model.name = [NSString stringWithFormat:@"全%@",model.name];
//                    _districtAry = @[model];
                }
            }
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.collectionView reloadData];
        });
    } failed:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
